package com.sskj.mqtt.many;

import java.util.regex.Pattern;

/**
 * @Author: Like
 * @Date: 2025/3/3 15:40
 * @Description: 匹配Topic
 */
public class TopicMatcher {
    public static Pattern compile(String topicFilter) {
        String regex = topicFilter
            .replaceAll("/\\+#$", "(/.*)?")          // 处理末尾的#通配符
            .replaceAll("\\+", "[^/]+")             // 处理+通配符
            .replaceAll("/#", "(/.*)?");            // 处理非末尾的#
        return Pattern.compile("^" + regex + "$");
    }

    public static boolean matches(String topicFilter, String actualTopic) {
        return compile(topicFilter).matcher(actualTopic).matches();
    }
}
